﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.IdentityModel.Tokens;
using SXFramWork.Core;
using SXFramWork.Service;
using SXFramWork.Service.Admin.AuthService.Models;

namespace SXFramWork.API.Controllers.Admin
{
    /// <summary>
    /// 身份认证授权
    /// </summary>
    public class AuthController : WebController
    {
        private readonly IAuthService _service;
        private readonly ICache _cache;
        private readonly JwtConfig _jwtConfig;
        private ILoginInfo _loginInfo;
        public AuthController(IAuthService authService,JwtConfig jwtConfig,ILoginInfo loginInfo,ICache cache)
        {
            _cache = cache;
            _loginInfo = loginInfo;
            _service = authService;
            _jwtConfig = jwtConfig;
        }
        /// <summary>
        /// 验证码
        /// </summary>
        /// <param name="length"></param>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        [Description("获取验证码")]
        public IApiResult VerifyCode(int length = 6)
        {
            return _service.CreateVerifyCode(length);
        }
        /// <summary>
        /// 验证登录状态请求接口
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<IApiResult> CheckLoginState()
        {
            if (_loginInfo.UserId.IsNull())
                return ApiResult.NotOk();
            else
                _cache.Set("uid", _loginInfo.UserId);
                return ApiResult.Ok();
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<IApiResult> Login([FromBody] LoginInput model)
        {
            var sw = new Stopwatch();
            sw.Start();
            var res = await _service.LoginAsync(model);
            sw.Stop();
           
            //写登录日志到数据库
            Loghelper.Default.writedblog(model.UserName, "登录系统",res.Msg, 1, res.Success == true ? 1 : 0, (sw.ElapsedMilliseconds).To_Int());
            if (!res.Success)
            {
                return res;
            }
            return LoginHandle(res);
        }
        /// <summary>
        /// 刷新令牌
        /// </summary>
        /// <param name="refreshToken"></param>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public async Task<IApiResult> RefreshToken([FromQuery]string refreshToken)
        {
            var result = await _service.RefreshToken(refreshToken);
            return LoginHandle(result);
        }
        /// <summary>
        /// 获取认证信息
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Common]
        public Task<IApiResult> AuthInfo()
        {
            return _service.GetAuthInfo();
        }
        /// <summary>
        /// 登录处理
        /// </summary>
        private IApiResult LoginHandle(ApiResult<LoginOutPut> result)
        {
            if (result.Success)
            {

                var user = result.Data.User;
                var loginInfo = result.Data.AuthInfo;
                var claims = new List<Claim>
                {
                    new Claim(ClaimNames.UserId, user.Id.ToString()),
                    new Claim(ClaimNames.UserName, user.UserName),
                    new Claim(ClaimNames.LoginTime, loginInfo.LoginTime.ToString()),
                    new Claim(ClaimNames.Platform, loginInfo.Platform.ToString()),
                };
                //生成token
                var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtConfig.SecurityKey));
                var signingCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

                var temp = new JwtSecurityToken(_jwtConfig.Issuer, _jwtConfig.Audience, claims, DateTime.Now, DateTime.Now.AddMinutes(_jwtConfig.Expires), signingCredentials);

                var token= new JwtSecurityTokenHandler().WriteToken(temp);
                var model = new
                {
                    AccessToken = token,
                    //过期时间(分钟)
                    ExpiresMinute = _jwtConfig.Expires,
                    RefreshToken = loginInfo.RefreshToken
                };
                _cache.Set("uid", user.Id);
                return ApiResult.Ok(model);
            }

            return ApiResult.NotOk(result.Msg);
        }
        /// <summary>
        /// 皮肤设置
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Common]
        public Task<IApiResult> Settheme([FromBody]string skin)
        {
            return _service.Settheme(skin);
        }


    }
}